package demo.demo3;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;

public class CoffeeFactory {
    private static HashMap<String,Object> map=new HashMap<String,Object>();
    static {

        try {
            //创建解析器
            SAXReader reader=new SAXReader();
            //解析xml文件
            Document document = reader.read("ch03/src/bean.xml");
            //获取根节点
            Element root = document.getRootElement();
            List<Element> list = root.elements("bean");
            for (Element element : list) {
                //获取id的属性和class属性
                String id = element.attributeValue("id");
                String aClass = element.attributeValue("class");
                //通过反射技术创建对象
                Class clazz=Class.forName(aClass);
                Object coffee = clazz.newInstance();
                //将对象存储
                map.put(id,coffee);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
    //根据id获取对象
    public static Object getBean(String id){
        return map.get(id);
    }
}
